package com.pinxixi.brand.service;

import com.pinxixi.brand.mapper.BrandMapper;
import com.pinxixi.framework.domain.brand.Brand;
import com.pinxixi.framework.domain.brand.response.BrandCode;
import com.pinxixi.framework.model.response.CommonCode;
import com.pinxixi.framework.model.response.ListResponseResult;
import com.pinxixi.framework.model.response.QueryResponseResult;
import com.pinxixi.framework.model.response.QueryResult;
import com.pinxixi.framework.model.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public ListResponseResult<Brand> findAll() {
        List list = brandMapper.findAll();
        QueryResult<Object> queryResult = new QueryResult<>();
        queryResult.setList(list);
        return new ListResponseResult<Brand>(CommonCode.SUCCESS,queryResult);
    }

    public ListResponseResult<Brand> findPage(Integer page, Integer size, Brand brand) {
        //当前页的数据
        Integer index = (page-1) * size;
        Map map = new HashMap();
        map.put("index",index);
        map.put("size",size);
        map.put("brand",brand);
        List<Brand> list = brandMapper.findPage(map);
        Integer total = brandMapper.findCount(brand);
        QueryResult<Brand> queryResult = new QueryResult<>();
        queryResult.setList(list);
        queryResult.setTotal(total);
        return new ListResponseResult<Brand>(CommonCode.SUCCESS,queryResult);
    }

    public QueryResponseResult<Brand> findOne(Long id) {
        Brand brand = brandMapper.findOne(id);
        if(brand == null){
            return new QueryResponseResult<>(BrandCode.BRAND_NOT_EXISTS,null);
        }
        return new QueryResponseResult<Brand>(CommonCode.SUCCESS,brand);
    }

    public QueryResponseResult<Brand> save(Brand brand) {
        if(brand.getId()==null){
            Brand brandDB = brandMapper.findByName(brand.getName());
            if(brandDB != null){
                return new QueryResponseResult<Brand>(BrandCode.BRAND_NAME_EXISTS,null);
            }
            brandMapper.add(brand);
        }else {
            brandMapper.edit(brand);
        }
        return new QueryResponseResult<Brand>(CommonCode.SUCCESS,brand);
    }

    public ResponseResult deleteById(Long id) {
        brandMapper.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public ResponseResult deleteAll(Long[] ids) {
        brandMapper.deleteAll(ids);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
